-module(tshark).

-export([tshark/1]).

%% tshark -i any -a duration:4 -c 10 -f "net 239.255.0.1 and port 7401" -T fields -e rtps.sm.seqNumber -Q

args(Opts) ->
    args(Opts, []).

args([], Args) ->
    lists:join(" ", ["-i any", "-l", "-n", "-q", "-Q"] ++ Args);
args([{packet_count, N} | Opts], Args) ->
    Arg = io_lib:format("-c ~B", [N]),
    args(Opts, [Arg | Args]);
args([{fields, Fields} | Opts], Args) ->
    Arg = lists:join(" ", ["-T fields" | [io_lib:format("-e ~s", [Field]) || Field <- Fields]]),
    args(Opts, [Arg | Args]);
args([{filter, Filter} | Opts], Args) ->
    Arg = io_lib:format("-f ~s", [Filter]),
    args(Opts, [Arg | Args]);
args([_Opt | Opts], Args) ->
    args(Opts, Args).
    
tshark(Opts) ->
    Args = args(Opts),
    Cmd = io_lib:format("tshark ~s", [Args]),
    Port = open_port({spawn, Cmd}, [binary, {line, 255}, exit_status, stderr_to_stdout]),
    io:format("Started...~n"),
    loop(Port).

loop(Port) ->
    receive
	{Port, {data, {eol, Data}}} ->
	    io:format("~p~n", [Data]),
%% 	    L1 = string:lexemes(Data, [$,]),
%% 	    L2 = [binary_to_integer(X, 16) || <<"0x", X/binary>> <- L1],
	    loop(Port);
	{Port, Output} when Output =:= {exit_status, 0}; Output =:= eof ->
	    io:format("Done~n");
	{Port, {exit_status, Status}} ->
	    io:format("Error ~p~n", [Status]),
	    error(Status);
	Rest ->
	    io:format("Rest ~p~n", [Rest]),
	    loop(Port)
    end.
	    
